#encoding:UTF-8
import os,sys
import urllib2
import re
import json
from datetime import date
from time import mktime
import datetime
from lib import pythonlibSB
from lib import mydb
import MySQLdb

c = mydb.WriteItem()
list_mien_bac = [1]
list_mien_trung = range(23,37)
list_mien_nam = range(2,23)
list_mien_nam.remove(10)
def getContent(url):
    try:
        respone = urllib2.urlopen(url)
        content = respone.read()
        return content
    except:
        return ''

def get_date(content):
    opentime = 0
    tmp = content
    pos1 = tmp.find('id="content"')
    pos2 = tmp.find('class="bottom_tbl_kq"',pos1)
    t = pythonlibSB.remove_tag(tmp[pos1:pos2])
    if t.find('KẾT QUẢ XỔ SỐ') != -1:
        reg = re.compile('([0-9]+)[/]([0-9]+)[/]([0-9]+)')
        if reg.search(t):
            ngay = int(reg.search(t).group(1))
            thang = int(reg.search(t).group(2))
            nam = int(reg.search(t).group(3))
            open_time = date(nam,thang,ngay)
            opentime = int(mktime(open_time.timetuple()))
               
    return opentime

def check_date(url_content):
    status = False
    open_date = get_date(url_content)
    date_now = date.today()
    current_date = int(mktime(date_now.timetuple()))
    if current_date == open_date:
        status = True
    return status
    


def getResult(str):
    mapName = {}
    tmp = str
    pos1 = tmp.find('<tr>')
    while pos1 != -1:
        pos2 = tmp.find('</tr>',pos1)
        if pos2 == -1:
            break
        t = tmp[pos1:pos2]
        reg = re.compile('(<td)(.*?)(class="tengiai")(.*?)>(.*?)(</td>)')
        if reg.search(t):
            cur_name = reg.search(t).group(5)
        reg2 = re.compile('(<td)(.*?)(class="number_kq")(.*?)>(.*?)(</td>)')
        if reg2.search(t):
            result = reg2.search(t).group(5)
            result = result.split('-')
            mapName[cur_name] = [i for i in result]
        pos1 = pos2 + 1
    return mapName


def convertMap(inMap,id_mien):
    outMap = {0:[],
              1:[],
              2:[],
              3:[],
              4:[],
              5:[],
              6:[],
              7:[],
              8:[]
              }
    if id_mien == 1:
        dbArr = inMap["Giải đặc biệt"]
        gnhatArr = inMap["Giải nhất"]
        gnhiArr = inMap["Giải nhì"]
        gbaArr = inMap["Giải ba"]
        gtuArr = inMap["Giải tư"]
        gnamArr = inMap["Giải năm"]
        gsauArr = inMap["Giải sáu"]
        gbayArr = inMap["Giải bảy"]
        gtamArr = []
    else:
        dbArr = inMap["Giải đặc biệt"]
        gnhatArr = inMap["Giải nhất"]
        gnhiArr = inMap["Giải nhì"]
        gbaArr = inMap["Giải ba"]
        gtuArr = inMap["Giải tư"]
        gnamArr = inMap["Giải năm"]
        gsauArr = inMap["Giải sáu"]
        gbayArr = inMap["Giải bảy"]
        gtamArr = inMap["Giải tám"]
    
    outMap[0] = []
    try:
        if len(dbArr) > 1:
            outMap[0] = [dbArr[1]]
        else:
            outMap[0] = [dbArr[0]]
    except:
        outMap[0] = []
    outMap[1] = gnhatArr
    outMap[2] = gnhiArr
    outMap[3] = gbaArr
    outMap[4] = gtuArr
    outMap[5] = gnamArr
    outMap[6] = gsauArr
    outMap[7] = gbayArr
    outMap[8] = gtamArr
    saveMap = []
    for i in range(9):
        buf = {}
        buf['id_giai'] = i
        buf['result'] = outMap[i]
        saveMap.append(buf)
    return json.dumps(saveMap)
    
def get_id_mien(id_tinh):
    if id_tinh in list_mien_bac:return 1
    if id_tinh in list_mien_trung:return 2
    if id_tinh in list_mien_nam:return 3
    
def saveContent():
    mapName = {}
    getUrlStr = 'SELECT * FROM url_mothuong WHERE `id_filter` = 0'
    list_data = c.excuteReturn(getUrlStr)
    mydate = date.today()
    current_date = mktime(mydate.timetuple())
    for data in list_data:
        id_tinh = data['id_tinh']
        url = data['url']
        print  url
        urlContent = getContent(url)
        id_mien = get_id_mien(id_tinh)
        if check_date(urlContent):
            tmp = urlContent
            pos1 = tmp.find('id="content"')
            pos2 = tmp.find('class="bottom_tbl_kq"',pos1)
            ketquatable = tmp[pos1:pos2]
            mapName = getResult(ketquatable)
            lastMap = MySQLdb.escape_string(convertMap(mapName,id_mien))
            insertContentStr = "CALL insert_ketqua_url('%s','%s','%s','%s')"\
                                 %(id_tinh,lastMap, current_date,id_mien)
            c.excuteNonReturn(insertContentStr)
            print "Lay xong 1 link"
    print "Lay xong tat ca"
    
if __name__ == "__main__":
    saveContent()